<template>
  <div class="filter-section">
    <span class="filter-label">金额范围</span>
    <div class="tag-container">
      <span
        v-for="tag in amountTags"
        :key="tag.value"
        class="text-tag"
        :class="{ active: tag.type === 'primary' }"
        @click="handleAmountTagClick(tag)"
      >
        <span class="text-tag-label">{{ tag.label }}</span>
        <span class="text-tag-close" @click.stop="handleAmountClose(tag)">×</span>
      </span>

      <div v-if="amountInputVisible" class="range-input-container">
        <el-input
          v-model="amountStartValue"
          class="tag-input"
          size="large"
          placeholder="开始金额"
          @keyup.enter="handleAmountInputConfirm"
        />
        <span class="range-separator">-</span>
        <el-input
          v-model="amountEndValue"
          class="tag-input"
          size="large"
          placeholder="结束金额"
          @keyup.enter="handleAmountInputConfirm"
        />
        <el-button type="primary" size="small" @click="handleAmountInputConfirm" class="confirm-btn"> 确认 </el-button>
        <el-button size="small" @click="amountInputVisible = false" class="cancel-btn"> 取消 </el-button>
      </div>
      <el-button v-else class="button-new-tag" size="large" @click="showAmountInput"> + 新增范围 </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue"
import { ElMessage } from "element-plus"
import {
  getAmountRangesAllListApi,
  createAmountRangeApi,
  deleteAmountRangeApi
} from "../../../../../api/calculator/index"
import type { TagItem, AmountRangeItem } from "./types"

// Props
interface Props {
  modelValue?: TagItem[]
  selectedTypeId?: number
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  selectedTypeId: undefined
})

// Emits
const emit = defineEmits<{
  "update:modelValue": [value: TagItem[]]
  change: [selectedRanges: TagItem[]]
  rangeSelect: [tag: TagItem]
}>()

// 票面金额标签数据
const amountTags = ref<TagItem[]>([])

// 输入框状态
const amountInputVisible = ref<boolean>(false)
const amountStartValue = ref<string>("")
const amountEndValue = ref<string>("")

// 监听选中的票据类型变化
watch(
  () => props.selectedTypeId,
  async (newTypeId) => {
    if (newTypeId) {
      await loadAmountRanges(newTypeId)
    } else {
      amountTags.value = []
      emit("update:modelValue", amountTags.value)
    }
  },
  { immediate: true }
)

/**
 * 处理票面金额标签点击（单选）
 * 点击后清空其他选中，仅保留当前，并刷新到期日期标签
 */
const handleAmountTagClick = async (tag: TagItem) => {
  // 单选：清空所有，再选中当前
  amountTags.value.forEach((t) => (t.type = ""))
  tag.type = "primary"

  emit("update:modelValue", amountTags.value)
  emit("rangeSelect", tag)

  const selectedRanges = amountTags.value.filter((t) => t.type === "primary")
  emit("change", selectedRanges)
}

/**
 * 删除票面金额标签
 * 删除后同步更新到期日期标签
 */
const handleAmountClose = async (tag: TagItem) => {
  // 解析区间ID（后端以 range_id 标识）
  const rangeId = Number(tag.value)
  if (!Number.isFinite(rangeId)) {
    ElMessage.error("无效的金额区间标识")
    return
  }

  try {
    const res = await deleteAmountRangeApi({ range_id: rangeId })
    if (res.code === 200) {
      ElMessage.success("删除金额范围成功")
      // 重新按当前选中票据类型加载金额范围
      if (props.selectedTypeId) {
        await loadAmountRanges(props.selectedTypeId)
      }
    } else {
      ElMessage.error(res.message || "删除金额范围失败")
    }
  } catch (error) {
    console.error("删除金额范围失败:", error)
    ElMessage.error("删除金额范围失败")
  }
}

// 显示金额范围输入框
const showAmountInput = () => {
  amountInputVisible.value = true
  amountStartValue.value = ""
  amountEndValue.value = ""
}

// 确认票面金额输入
const handleAmountInputConfirm = async () => {
  const startValue = amountStartValue.value.trim()
  const endValue = amountEndValue.value.trim()

  if (!startValue && !endValue) {
    amountInputVisible.value = false
    amountStartValue.value = ""
    amountEndValue.value = ""
    return
  }

  try {
    let label = ""
    let minAmount = ""
    let maxAmount = ""

    if (startValue && endValue) {
      label = `${startValue}-${endValue}`
      minAmount = startValue
      maxAmount = endValue
    } else if (startValue) {
      // 只有开始值，表示"以上"
      label = `${startValue}以上`
      minAmount = startValue
      maxAmount = "999999" // 设置一个较大的上限值
    } else if (endValue) {
      // 只有结束值，表示"以下"
      label = `${endValue}以下`
      minAmount = "0"
      maxAmount = endValue
    }

    // 获取当前选中的票据类型ID
    const typeId = props.selectedTypeId || 1

    // 调用API创建新的金额范围
    const response = await createAmountRangeApi({
      name: label,
      type_id: typeId,
      min_amount: minAmount,
      max_amount: maxAmount
    })

    if (response.code === 200) {
      ElMessage.success("新增金额范围成功")

      // 重新加载金额范围数据
      await loadAmountRanges(typeId)
    } else {
      ElMessage.error(response.message || "新增金额范围失败")
    }
  } catch (error) {
    console.error("创建金额范围失败:", error)
    ElMessage.error("新增金额范围失败")
  }

  amountInputVisible.value = false
  amountStartValue.value = ""
  amountEndValue.value = ""
}

// 加载金额范围数据
const loadAmountRanges = async (bankTypeId?: number) => {
  amountTags.value = []
  try {
    const params: any = {}
    if (bankTypeId) {
      params.type_id = bankTypeId
    }

    const response = await getAmountRangesAllListApi(params)
    console.log("金额范围API响应:", response)

    if (response.code === 200 && response.data?.data && response.data.data.length > 0) {
      const amountRanges = response.data.data as AmountRangeItem[]

      // 将API返回的金额范围数据转换为标签格式
      amountTags.value = amountRanges.map((item, index) => ({
        label: item.name, // 使用API返回的name字段作为显示标签
        value: item.range_id.toString(), // 使用range_id作为值
        type: index === 0 ? "primary" : "" // 默认选中第一个
      }))

      console.log("转换后的金额标签:", amountTags.value)

      emit("update:modelValue", amountTags.value)

      // 触发选中事件
      const selectedRanges = amountTags.value.filter((t) => t.type === "primary")
      if (selectedRanges.length > 0) {
        emit("change", selectedRanges)
        emit("rangeSelect", selectedRanges[0])
      }
    } else {
      // 如果API没有返回数据，清空金额标签
      amountTags.value = []
      emit("update:modelValue", amountTags.value)
      if (bankTypeId) {
        ElMessage.error("请先设置金额区间")
      }
      console.log("API未返回金额范围数据，金额标签已清空")
    }
  } catch (error) {
    console.error("加载金额范围失败:", error)
    ElMessage.error("加载金额范围失败")

    // 出错时清空金额标签
    amountTags.value = []
    emit("update:modelValue", amountTags.value)
  }
}

// 暴露方法给父组件
defineExpose({
  loadAmountRanges,
  getSelectedRanges: () => amountTags.value.filter((t) => t.type === "primary")
})
</script>

<style scoped>
.filter-section {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.filter-label {
  font-weight: 500;
  color: #333;
  margin-right: 15px;
  min-width: 70px;
  font-size: 14px;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-right: 20px;
}

.tag-input {
  width: 90px;
}

.range-input-container {
  display: flex;
  align-items: center;
  gap: 5px;
}

.range-separator {
  color: #666;
  font-weight: bold;
  margin: 0 5px;
}

.confirm-btn,
.cancel-btn {
  margin-left: 5px;
}

.button-new-tag {
  border-style: dashed;
  color: #999;
}

.button-new-tag:hover {
  color: #409eff;
  border-color: #409eff;
}

/* 文本标签样式（替代 el-tag） */
.text-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  color: #666;
  border: 1px solid transparent;
  user-select: none;
}
.text-tag:hover {
  color: #409eff;
}
.text-tag.active {
  color: #409eff;
  font-weight: 500;
  border-color: rgba(64, 158, 255, 0.2);
  background-color: rgba(64, 158, 255, 0.05);
}
.text-tag-close {
  margin-left: 4px;
  color: #bbb;
  font-weight: bold;
  cursor: pointer;
}
.text-tag-close:hover {
  color: #f56c6c;
}
.text-tag-label {
  line-height: 1;
}
</style>
